package lab2task3;

/**
 * 
 * Buffer class of circular buffer implementation 
 *  without using java.util.concurrent
 * 
 * @author Bulaev Igor
 *
 */

public class BoundedBuffer {

	private char[] buffer;
	private final int size;
	private int in;
	private int out;
	private int count;

	public BoundedBuffer(int size) {
		this.size = size;
		buffer = new char[size];
	}

	public synchronized void put(char c) throws InterruptedException {
		while (count == buffer.length) {
			wait();
		}
		buffer[in] = c;
		in = (in + 1) % size;
		count++;
		notifyAll();
		System.out.println("Put " + in + ". Total: " + count);
	}

	public synchronized char take() throws InterruptedException {
		while (count == 0) {
			wait();
		}
		out = (out + 1) % size;
		count--;
		notifyAll();
		System.out.println("Taken " + out + ". Total: " + count);
		return buffer[out];
	}

}
